

package cn.shengchao.examstar.account.acl.adapters.repositories;

import cn.shengchao.examstar.account.acl.ports.repositories.IBankCardRepository;
import cn.shengchao.examstar.account.domain.BankCard;
import cn.shengchao.examstar.account.infrastructure.dao.UserBankCardDao;
import cn.shengchao.examstar.account.infrastructure.dao.po.TUserBankCard;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Repository
public class BankCardRepository implements IBankCardRepository {

    @Autowired
    private UserBankCardDao userBankCardDao;

    @Override
    public void save(BankCard bankCard, long userId) {
        TUserBankCard tUserBankCard = new TUserBankCard();
        tUserBankCard.setBankCard(bankCard.getCardNo());
        tUserBankCard.setBankOfDeposit(bankCard.getBankOfDeposit());
        tUserBankCard.setUserId(userId);
        userBankCardDao.insert(tUserBankCard);
    }

    @Override
    public void delete(long id) {
        userBankCardDao.deleteById(id);
    }

    @Override
    public List<BankCard> findByUserId(long userId) {
        List<TUserBankCard> userBackCard = userBankCardDao.selectList(new LambdaQueryWrapper<TUserBankCard>()
            .eq(TUserBankCard::getUserId, userId));
        return userBackCard.stream().map(tUserBankCard -> {
            BankCard bankCard = new BankCard();
            bankCard.setId(tUserBankCard.getId());
            bankCard.setCardNo(tUserBankCard.getBankCard());
            bankCard.setBankOfDeposit(tUserBankCard.getBankOfDeposit());
            return bankCard;
        }).collect(Collectors.toList());
    }

    @Override
    public Optional<BankCard> findById(String backCardId) {
        TUserBankCard tUserBankCard = userBankCardDao.selectById(backCardId);
        if (tUserBankCard == null) {
            return Optional.empty();
        }
        BankCard bankCard = new BankCard();
        bankCard.setId(tUserBankCard.getId());
        bankCard.setCardNo(tUserBankCard.getBankCard());
        bankCard.setBankOfDeposit(tUserBankCard.getBankOfDeposit());
        bankCard.setUserId(tUserBankCard.getUserId());
        return Optional.of(bankCard);
    }
}
